package de.g18.gruppe3.gui.controller;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import de.g18.gruppe3.common.exception.ServiceException;
import de.g18.gruppe3.common.exception.WrongUsernameAndOrPasswordException;
import de.g18.gruppe3.common.model.AccountAdmin;
import de.g18.gruppe3.gui.helper.AbstractAction;
import de.g18.gruppe3.gui.view.UMLoginView;
import de.g18.gruppe3.ldapinterface.service.provider.LDAPServiceProvider;

public class UMLoginViewController {

	private final UMLoginView loginView;
	private final AccountAdmin accountAdmin;
	private final AbstractAction loginAction;

	public UMLoginViewController() {
		loginView = new UMLoginView("Benutzer anmelden");
		accountAdmin = new AccountAdmin(null, null);
		loginAction = new UserLoginOK();

		loginView.getbUCLoginOk().addActionListener(loginAction);
		loginView.getbUCLoginChancel().addActionListener(new UserLoginChancel());

		loginView.gettfUCLoginViewLogin().addKeyListener(new PressEnter());
		loginView.getpfCLoginViewPasswort().addKeyListener(new PressEnter());
	}


	// Inner Classes ***********************************************************

	private class UserLoginOK extends AbstractAction {
		@Override
		public void execute(ActionEvent arg0) throws WrongUsernameAndOrPasswordException, ServiceException {
			accountAdmin.setLogin(loginView.gettfUCLoginViewLogin().getText());
			accountAdmin.setPasswort(new String(loginView.getpfCLoginViewPasswort().getPassword()));

			LDAPServiceProvider.getInstance().getLoginService().login(accountAdmin);

			loginView.dispose();
			new UMViewController(new UserController());
		}
	}

	private class UserLoginChancel extends AbstractAction {
		@Override
		public void execute(ActionEvent arg0) {
			loginView.dispose();
		}
	}

	private class PressEnter implements KeyListener {
		@Override
		public void keyTyped(KeyEvent arg0) {

		}

		@Override
		public void keyReleased(KeyEvent arg0) {
		}

		@Override
		public void keyPressed(KeyEvent arg0) {
            if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
                loginAction.actionPerformed(null);
            }
		}
	}
}
